package com.zhangtai.modules.controller.admin;

import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.AuthorityLogDao;
import com.zhangtai.modules.dao.UserDao;
import com.zhangtai.modules.dto.AuthorityLogDto;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.system.AuthorityLogEntity;
import com.zhangtai.modules.entity.system.UserEntity;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.system.AuthorityLogService;
import com.zhangtai.utils.DateUtils;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;


@RestController
@Api(tags="用户行为记录接口")
@RequestMapping("userUpdateInfo")
@Slf4j
public class AuthorityLogController {
    @Autowired
    private AuthorityLogService authorityLogService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private UserDao userDao;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private AuthorityLogDao authorityLogDao;

    @PostMapping("/getSysAuthorityLogPage")
    @ApiOperation(value="分页查询用户行为记录")
    @PreAuthorize("hasAuthority('sys:admin:get')")
    public R getSysAuthorityLogPage(@RequestBody @Valid AuthorityLogDto authorityLogDto,HttpServletRequest request) throws Exception {

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        String startTime="",endTime="";
        if (authorityLogDto.getStartTime()!=null){
            startTime= DateUtils.format(authorityLogDto.getStartTime(),"yyyy-MM-dd")+" 00:00:00";
        }
        if (authorityLogDto.getStartTime()!=null){
             endTime = DateUtils.format(authorityLogDto.getEndTime(),"yyyy-MM-dd")+" 23:59:59";
        }
        PageResult pageResult= authorityLogService.queryPage(orgIds,authorityLogDto.getUpdateUserName(),
                 authorityLogDto.getJobName(),
                 authorityLogDto.getMethod(),
                authorityLogDto.getType(),
                 startTime,
                 endTime,
                authorityLogDto.getRemark(),
                 authorityLogDto.getParams(),
                 authorityLogDto.getPageNum(),
                 authorityLogDto.getPageSize()
                 );

        return R.ok(pageResult);
    }

    @PostMapping("/getSysAuthorityLogByOidPage")
    @ApiOperation(value="根据oid分页查询用户修改入职日期记录")
    @PreAuthorize("hasAuthority('sys:admin:get')")
    public R getSysAuthorityLogByOidPage(  @RequestParam( value = "oid") String oid,
                                           @RequestParam( value = "pageNum" ,defaultValue = "1") Integer pageNum,
                                           @RequestParam( value = "pageSize" ,defaultValue = "10") Integer pageSize) {
        PageResult pageResult=  authorityLogService.queryPageBYOid(oid,pageNum,pageSize);
        return R.ok(pageResult);
    }

    @PostMapping("/saveUserUpdateHiredateInfo")
    @ApiOperation(value="用户修改入职日期记录添加")
    @SysAuthorityLog(value = "用户修改入职日期记录添加")
    @PreAuthorize("hasAuthority('sys:admin:update')")
    public R saveUserUpdateHiredateInfo(@RequestParam("hiredate") String hiredate,
                                        @RequestParam("newHiredate") String newHiredate,
                                        @RequestParam("oid") Long oid,
                                        @RequestParam( value = "remark" ,required = false) String remark,
                                        @RequestParam( value = "type" ,defaultValue = "1") Integer type, HttpServletRequest request )throws Exception {

        AuthorityLogEntity authorityLogEntity=new AuthorityLogEntity();
        JSONObject userInfo=  loginController.getUserInfo(request).getData();
        log.info("获取登录用户信息user:{}",userInfo);
        if(!ObjectUtils.isEmpty(userInfo)){
            UserEntity userEntity=userDao.selectById(userInfo.getLong("id"));
            authorityLogEntity.setJobId(userEntity.getJobId());
            authorityLogEntity.setJobName(userEntity.getJobname());
            authorityLogEntity.setUpdateUserName(userEntity.getName());
            authorityLogEntity.setUsercode(userEntity.getUsercode());
            authorityLogEntity.setUpdateUserId(userEntity.getUserId());
            authorityLogEntity.setIp(ServletUtil.getClientIP(request));
        }
        authorityLogEntity.setOid(oid);
        authorityLogEntity.setType(type);
        authorityLogEntity.setOldData(hiredate);
        authorityLogEntity.setNewData(newHiredate);
        authorityLogEntity.setIsDelete(0);
        authorityLogEntity.setUpdateTime(new Date());
        authorityLogEntity.setRemark(remark);
        EmployeeInfoEntity employeeInfoEntity=new EmployeeInfoEntity();
        employeeInfoEntity.setOid(oid);
        employeeInfoEntity.setUpdateEntryStatus(1);
        employeeInfoService.updateByIdE(employeeInfoEntity);
        return authorityLogService.saveE(authorityLogEntity);
    }





    @PostMapping("/getgetSysAuthorityLogByoidAndtype")
    @ApiOperation(value="根据修修的员工id和记录类型查询记录")
    @PreAuthorize("hasAuthority('sys:admin:get')")
    public R getgetSysAuthorityLogByoidAndtype(@RequestParam("oid") Long oid,@RequestParam( value = "type" ,defaultValue = "1") Integer type )throws Exception {
       List<AuthorityLogEntity> authorityLogEntityList= authorityLogDao.selectList(new QueryWrapper<AuthorityLogEntity>()
               .eq("is_delete", "0")
               .eq("oid", oid)
               .eq("type", type)
               .orderByDesc("update_time"));

        return R.ok(authorityLogEntityList);
    }

}
